package com.kira.solo.schedule.domain

import android.content.Context
import androidx.datastore.dataStore
import com.kira.solo.schedule.pojo.CasePeriodTaskInfo
import com.kira.solo.schedule.pojo.CasePeriodTaskInfoGroup
import com.kira.solo.schedule.utils.jsonSerializer
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 定时任务维护服务
 * @packageName com.kira.solo.schedule.domain
 * @date 2024/1/25 15:56
 * @author zhanglei
 */
@Singleton
class ScheduleTasksService @Inject constructor(@ApplicationContext private val context: Context) {
    private val tasks = context.schedule

    /**
     * 所有定时任务
     */
    val scheduledTasks = tasks.data.map { it.taskMap.values }.distinctUntilChanged()

    suspend fun get(taskId: Long): List<Long> {
        return tasks.data.firstOrNull()?.taskMap?.get(taskId)?.caseIds ?: emptyList()
    }

    suspend fun getTask(taskId: Long): CasePeriodTaskInfo? {
        return tasks.data.firstOrNull()?.taskMap?.get(taskId)
    }


    /**
     * 删除
     */
    suspend fun deleteTask(casePeriodTaskInfo: CasePeriodTaskInfo) {
        tasks.updateData {
            it.copy(
                taskMap = it.taskMap.toMutableMap().apply { remove(casePeriodTaskInfo.taskId) })
        }
    }

    /**
     * 增加
     */
    suspend fun addTask(casePeriodTaskInfo: CasePeriodTaskInfo) {
        tasks.updateData {
            it.copy(
                taskMap = it.taskMap.toMutableMap()
                    .apply {
                        val taskId = System.currentTimeMillis()
                        this[System.currentTimeMillis()] = casePeriodTaskInfo.copy(taskId = taskId)
                    })
        }
    }

    /**
     * 修改
     */
    suspend fun modifyTask(casePeriodTaskInfo: CasePeriodTaskInfo) {
        tasks.updateData {
            if (it.taskMap.containsKey(casePeriodTaskInfo.taskId)) {
                it.copy(
                    taskMap = it.taskMap.toMutableMap()
                        .apply { this[casePeriodTaskInfo.taskId] = casePeriodTaskInfo })
            } else it
        }
    }
}

/**
 * 定时器信息存储文件
 */
val Context.schedule by dataStore(
    "schedule_tasks",
    jsonSerializer { CasePeriodTaskInfoGroup.INIT })